/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.absisgroup.nsc.utilities;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import java.util.TimeZone;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author Hue
 */
public class Util {
    private static final int BUFFER_SIZE = 4096;
    
    public static Date toDate(final String _strText, final String _strPattern) {
        if(isNullOrEmpty(_strText) || isNullOrEmpty(_strPattern)) {
            return null;
        }
        try {
            final SimpleDateFormat df = new SimpleDateFormat(_strPattern);
            return df.parse(_strText);
        }
        catch(Exception ex) {
            return null;
        }
    }
    
    public static java.sql.Date toSQLDate(final String _strText, final String _strPattern) {
        if(isNullOrEmpty(_strText) || isNullOrEmpty(_strPattern)) {
            return null;
        }
        try {
            final Date d = toDate(_strText,_strPattern);
            return (d == null ? null : new java.sql.Date(d.getTime()));
        }
        catch(Exception ex) {
            return null;
        }
    }

    public static java.sql.Timestamp toTimestamp(final String _strText, final String _strPattern) {
        if(isNullOrEmpty(_strText) || isNullOrEmpty(_strPattern)) {
            return null;
        }
        try {
            final Date d = toDate(_strText,_strPattern);
            return (d == null ? null : new java.sql.Timestamp(d.getTime()));
        }
        catch(Exception ex) {
            return null;
        }
    }
    
    public static Date newDate() {
        TimeZone zone = TimeZone.getTimeZone("GMT+7");
        TimeZone.setDefault(zone);
        Calendar cal = Calendar.getInstance(zone);
        return cal.getTime();
    }
    
    public static Date newSQLDate() {
        Date d = newDate();
        return new java.sql.Date(d.getTime());
    }
    
    public static Timestamp newTimestamp() {
        Date d = newDate();
        return new Timestamp(d.getTime());
    }
    
    public static BigDecimal toBigDecimal(final String _strValue) {
        if(isNullOrEmpty(_strValue)) {
            return null;
        }
        try {
            return new BigDecimal(_strValue);
        }
        catch(NumberFormatException ex) {
            return null;
        }
    }
    
    public static String toString(final Date date, final String _strPattern) {
        if(date == null || isNullOrEmpty(_strPattern)) {
            return null;
        }
        try {
            final SimpleDateFormat df = new SimpleDateFormat(_strPattern);
            return df.format(date);
        }
        catch(Exception ex) {
            return null;
        }
    }
    
    public static int toInt(final String _strValue) {
        if(isNullOrEmpty(_strValue)) {
            return 0;
        }
        try {
           return Integer.parseInt(_strValue);
        }
        catch(NumberFormatException ex) {
            return 0;
        }
    }
    
    public static Properties getAppTexts(ServletContext context) throws Exception {
        Properties texts = (Properties) context.getAttribute("UTIL_APP_TEXTS");
        if(texts == null) {
            texts = new Properties();
            FileInputStream in = new FileInputStream(context.getRealPath("WEB-INF/texts.properties"));
            texts.load(in);
            in.close();
            
            context.setAttribute("UTIL_APP_TEXTS", texts);
        }
        return texts;
    }
    
    public static String replace(final String _str, final String _strOld, final String _strNew) {
        if(_str == null || _strOld == null || _strNew == null || _str.indexOf(_strOld) == -1) {
            return _str;
        }
        StringBuffer sb = new StringBuffer(_str);
        int iIndex = 0;
        while((iIndex = sb.indexOf(_strOld,iIndex)) != -1) {
            sb = sb.replace(iIndex,iIndex+_strOld.length(),_strNew);
            iIndex += _strNew.length();
        }
        
        return sb.toString();
    }
    
    public static String calculateDuration(final Date startTime, final Date endTime) {
        try {
            final Calendar scal = Calendar.getInstance();
            final Calendar ecal = Calendar.getInstance();
            scal.setTime(startTime);
            ecal.setTime(endTime);

            final int s1 =  scal.get(Calendar.HOUR_OF_DAY) * 3600 + scal.get(Calendar.MINUTE) * 60 + scal.get(Calendar.SECOND);
            final int s2 =  ecal.get(Calendar.HOUR_OF_DAY) * 3600 + ecal.get(Calendar.MINUTE) * 60 + ecal.get(Calendar.SECOND);

            scal.set(Calendar.HOUR_OF_DAY, 0);
            scal.set(Calendar.MINUTE, 0);
            scal.set(Calendar.SECOND, (s2 - s1));
            return new SimpleDateFormat("HH:mm:ss").format(scal.getTime());
        }
        catch(Exception ex) {
            return "00:00:00";
        }
    }
    
    public static boolean isNullOrEmpty(final String value) {
        return (value == null || value.length() == 0);
    }
    
    public static byte[] readFile(final String filename) throws Exception {
        final FileInputStream in = new FileInputStream(filename);
        final byte[] data = readData(in);
        in.close();
        
        return data;
    }
    
    public static byte[] readData(final InputStream in) throws java.io.IOException {
        final ByteArrayOutputStream baOut = new ByteArrayOutputStream();
        int nByte = 0;
        final byte[] buff = new byte[BUFFER_SIZE];
        while((nByte = in.read(buff)) > 0) {
            baOut.write(buff,0, nByte);
        }
        final byte[] data = baOut.toByteArray();
        baOut.close();
        
        return data;
    }
    
    public static void writeFile(final String filename, final byte[] data) throws FileNotFoundException, IOException {
        writeFile(filename, data, false);
    }
    
    public static void writeFile(final String filename, final byte[] data, final boolean append) throws FileNotFoundException, IOException {
        if(filename == null || data == null) {
            return;
        }
        final FileOutputStream out = new FileOutputStream(filename, append);
        out.write(data);
        out.close();
    }
    
    public static String hashPassword(final String _str) {
        long h = 0;
        final int length = _str.length();
        for(int i=0;i<length; i++) {
            h = h * 31 + _str.charAt(i);
        }

        String hs = String.valueOf(h);
        while (hs.length() < 15) {
            h = h*7;
            hs += String.valueOf(h);
        }

        return hs.substring(0,15);
    }
}
